package com.shizhanzhe.gxb;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.shizhanzhe.gxb.base.UserBean;
import com.shizhanzhe.gxb.my.bean.Login;
import com.shizhanzhe.gxb.my.bean.WxLoginBean;
import com.shizhanzhe.gxb.url.Path;
import com.shizhanzhe.gxb.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.gxb.utils.SharedPreferencesUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * @author YJ
 * @date 2019/1/17
 */
public class WXLoginActivity extends Activity {

    private Platform wechat;
    ProgressDialog dialog;
    private String content = "";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wx_login);
        ImmersionBar.with(this)
                .transparentBar()
                .init();
        ButterKnife.bind(this);
        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
        dialog.setCancelable(true);// 设置是否可以通过点击Back键取消
        dialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        dialog.setMessage("正在登录...Loading");
    }

    @OnClick(R.id.wx_login)
    public void onViewClicked() {
        dialog.show();
        ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData data = cm.getPrimaryClip();
        if (data !=null) {
            ClipData.Item item = data.getItemAt(0);
//        content = item.getText().toString();
            if (item.getText().toString().length() >= 5 && item.getText().toString().length() < 10) {
                try {
                    content = Integer.parseInt(item.getText().toString()) + "";
                } catch (Exception e) {
                }
            }
        }
        wechat = ShareSDK.getPlatform(Wechat.NAME);
        if (!isInstallApp(this,"com.tencent.mm")){
            Toast.makeText(this, "微信未安装,请先安装微信", Toast.LENGTH_SHORT).show();
            return;
        }
        if (wechat.isAuthValid()) {
            wechat.removeAccount(true);//执行此操作就可以移除掉本地授权状态和授权信息
        }
        wechat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, final HashMap<String, Object> hashMap) {
                Log.d("____",platform.getDb().exportData());
                final WxLoginBean loginBean = new Gson().fromJson(platform.getDb().exportData(), WxLoginBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OkHttpDownloadJsonUtil.downloadJson(WXLoginActivity.this, Path.wxlogin(loginBean.getUnionid(), loginBean.getOpenid(), loginBean.getNickname(), loginBean.getIcon(),content), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                            @Override
                            public void onsendJson(String json) {
                                Log.d("____",Path.wxlogin(loginBean.getUnionid(), loginBean.getOpenid(), loginBean.getNickname(), loginBean.getIcon(),content));
                                if (!"1".equals(json)&& !"2".equals(json)) {
                                    try {
                                        JSONObject object = new JSONObject(json);
                                        if (object.optInt("status") == 1) {
                                            Gson gson = new Gson();
                                            Login user = gson.fromJson(json, Login.class);
                                            UserBean.uid = user.getData().getUid();
                                            UserBean.pid = user.getData().getPuid();
                                            UserBean.mobile = user.getData().getMobile();
                                            UserBean.headimg = user.getData().getAvatar();
                                            UserBean.nickname = user.getData().getUname();
                                            UserBean.balance = user.getData().getMoney();
                                            UserBean.isuser = user.getData().getIsuser();
                                            UserBean.level = user.getData().getLevel();
                                            SharedPreferencesUtils.setParam(WXLoginActivity.this, "uid", UserBean.uid);
                                            SharedPreferencesUtils.setParam(WXLoginActivity.this, "pid", UserBean.pid);
                                            SharedPreferencesUtils.setParam(WXLoginActivity.this, "mobile", UserBean.mobile);
                                            SharedPreferencesUtils.setParam(WXLoginActivity.this, "headimg", UserBean.headimg);
                                            SharedPreferencesUtils.setParam(WXLoginActivity.this, "nickname", UserBean.nickname);
                                            SharedPreferencesUtils.setParam(WXLoginActivity.this, "balance", UserBean.balance);
                                            SharedPreferencesUtils.setParam(WXLoginActivity.this, "isuser", UserBean.isuser);
                                            SharedPreferencesUtils.setParam(WXLoginActivity.this, "level", UserBean.level);
                                            startActivity(new Intent(WXLoginActivity.this, MainActivity.class));
                                            finish();
                                        } else {
                                            dialog.dismiss();
                                            Toast.makeText(WXLoginActivity.this, object.optString("info"), Toast.LENGTH_SHORT).show();
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                        Log.d("___",json);
                                    }
                                } else {
                                    Toast.makeText(WXLoginActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                });
            }


            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WXLoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onCancel(Platform platform, int i) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WXLoginActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        wechat.showUser(null);
    }
    public static boolean isInstallApp(Context context, String PACK_NAME) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName.toLowerCase(Locale.ENGLISH);
                if (pn.equals(PACK_NAME)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }
}
